<!--
**********************************************************
* @Author: 张小平
* @Date:   2024-05-01
* @Email:  qqshuqian@163.com
* @Last modified: 最后修改日期
* @Description: 文件描述
**********************************************************
-->
<template >
    <div :style="{ backgroundColor: option.bgColor ,backgroundImage: 'url(' +  option.bgImg + ')',minHeight:'100%'}" >

     <div  v-if="option.carousels">
         <el-carousel indicator-position="outside">
             <el-carousel-item v-for="item in option.carousels" >
                 <h3>{{ item }}</h3>
             </el-carousel-item>
         </el-carousel>
     </div>
    <div class="formDiv" :style="{ backgroundColor: option.bgColor ,marginLeft: (option.bgMargin||0)+'%',marginRight: (option.bgMargin||0)+'%'}">
        <basic-container >

        </basic-container>

    </div>

    </div>
</template>


<script>
    import {getFormModel,} from "@/framework-admin/api/code/formmodel";
    import request from '@/framework-core/axios';
    import website from '@/framework-core/config/website';
    import router from '@/framework-core/router';
    export default {

        data() {
            return {}

        },
        created() {
            this.getFormInfo();
        },

        methods: {
            getFormInfo() {
                this.formId = this.$route.query.formId
                this.flowId = this.$route.query.flowId
                if (this.formId) {
                    this.loadData(this.formId)
                    this.dataId = this.$route.query.dataId
                    if (this.dataId) {
                        this.loadFormData(this.formId,this.dataId)
                    }
                }
            },
            loadData(formId) {
                getFormModel(formId)
                    .then((res) => {
                        if (res.data) {
                            this.option = eval("(" + res.data.data.data.modelJson + ")") || {};
                            if (this.option && this.option.column && this.option.column.length > 0) {
                                for (var iindex = 0; iindex < this.option.column.length; iindex++) {
                                    var $column = this.option.column[iindex];
                                    if ($column.links) {
                                        var linksEvent = $column.linksEvent;
                                        var linksEventRule = $column.linksEventRule;
                                        var linkList = $column.links.split(";")
                                        for (var yindex = 0; yindex < linkList.length; yindex++) {
                                            var unwatch = this.$watch('form.' + linkList[yindex], (newVal, oldVal) => {
                                                if (linksEvent == 1) {
                                                    $column.display = newVal != linksEventRule;

                                                } else if (linksEvent == 2) {

                                                }
                                                this.$message.error("newVal:" + newVal + "oldVal:" + oldVal)
                                            });
                                            this.unwatchs.push(unwatch)
                                        }
                                        //unwatch() // 之后取消观察
                                    }
                                }

                            }
                        }
                    })
                    .catch((err) => {
                        this.$message.error(err.msg || err.message)
                    })
                    .finally(() => {
                        this.loading = true
                    })
            },

            loadFormData(formId,dataId) {

                getDataByFormId(formId,dataId)
                    .then((res) => {
                        this.form = res.data.data.data;


                    })
                    .catch((err) => {
                        this.$message.error(err.msg || err.message)
                    })
                    .finally(() => {
                        this.loading = true
                    })
            },
            withTask(prefix) {
                return _.filter(this.taskFormPropertyList, (o) => {
                    const {id, value} = o;
                    return id.startsWith(prefix) && value === 'false';
                });
            },

            /**
             * 保存并提交后猜你喜欢
             */
            goToSuccess() {
                let submitSuccessPrompt = this.getSuccessPrompt('submitSuccessPrompt');
                const {routeType, hiddenButton} = this.$route.query;
                let query = {
                    processInstanceId: this.keyInfo.processInstanceId,
                    businessKey: this.keyInfo.businessKey,
                    submitSuccessPrompt: submitSuccessPrompt,
                    isIframe: this.$route.query.isIframe,
                    routeType: routeType
                };
                if (hiddenButton) {
                    query.hiddenButton = hiddenButton;
                }
                if (this.$route?.query?.appId) {
                    query.appId = this.$route.query.appId;
                }
                let nextRouterPath =
                    routeType === 'page' ? '/workflow/page/complete' : '/workflow/complete';
                if (this.$route.query?.titleHidden == 1) {
                    query.titleHidden = 1;
                }
                this.$router.push({
                    path: nextRouterPath,
                    query: query
                });
            },
            goToSuccess2(businessKey) {
                const {toNext, formId, routeType, titleHidden, hiddenButton} =
                    this.$route.query;
                if (toNext === 'true') {
                    let nextRouterPath =
                        routeType === 'page'
                            ? '/workflow/page/complete2'
                            : '/workflow/complete2';
                    this.$router.push({
                        path: nextRouterPath,
                        query: {
                            toNext,
                            formId,
                            businessKey,
                            routeType,
                            titleHidden,
                            hiddenButton
                        }
                    });
                }
            },
            toSign() {
                this.signFillUnitInfo.show = true;
                this.$refs.signFill.getFormEvent();
            },
            signSubmit(data, formId, done, errorDone) {
                request
                    .post(website.baseCodeApiUrl +
                        `/form-instance/sign-save?isSubmitProcess=true&formId=${formId}&procDefId=${this.processDefinitionId}`,
                        data
                    )
                    .then((response) => {
                        request
                            .post(website.baseCodeApiUrl +
                                `/flow-ext/do-task?taskId=${this.keyInfo.taskId}`,
                                response.data
                            )
                            .then(() => {
                                this.$message.success('会签成功！');
                                this.goToSuccess();
                                done();
                            })
                            .catch((error) => {
                                errorDone();
                                // this.$message.error(error.msg || error.message)
                            });
                    })
                    .catch((error) => {
                        errorDone();
                        // this.$message.error(error.msg || error.message)
                    });
            },
            /**
             * @auth ZHJI
             * 获取按钮的权限
             */
            getButtonAuth() {
                let url;
                if (
                    this.pageKey === 'DO' &&
                    this.keyInfo.taskId
                ) {
                    url = `/flow-task-change/do-task-form-button-authority?taskId=${this.keyInfo.taskId}`;
                } else if (this.keyInfo.processInstanceId) {
                    url = `/flow-task-change/view-form-button-authority?processInstanceId=${this.keyInfo.processInstanceId}`;
                }
                if (url) {
                    request
                        .get(website.baseCodeApiUrl + url)
                        .then((response) => {
                            Object.keys(this.buttonAuth).forEach((item) => {
                                this.buttonAuth[item].display = false;
                                this.buttonAuth[item].info = false;
                            });
                            Object.assign(this.buttonAuth, response.data);
                        })
                        .catch((error) => {
                            // this.$message.error(error.msg || error.message)
                        });
                }
            },
            /**
             * @auth ZHJI
             * 查看流程审批详情
             */
            getAuditDetail() {
                this.auditDetailInfo.businessKey = this.modelData.id;
                this.auditDetailInfo.formId = this.option.formId;
                this.auditDetailInfo.processInstanceId =
                    this.keyInfo.processInstanceId;
                this.auditDetailInfo.show = true;
            }, // 取消委派 , 只需要收集原因
            undoDelegateTask() {
                this.taskChange.choosePerson = false;
                this.taskChange.changeKey = 'cancelDelegate';
                this.taskChange.changeName = '取消委派';
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            ccProc() {
                // 抄送流程
                this.taskChange.choosePerson = true;
                this.taskChange.changeKey = 'cc';
                this.taskChange.changeName = '抄送';
                this.taskChange.maxRows = 50;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            // 取消委派回调函数
            cancelDelegate(data, done, errorDone) {
                request.delete(
                    website.baseCodeApiUrl +
                    '/flow-task-change/undo-delegate-task',
                    {
                        params: {
                            taskId: this.keyInfo.taskId,
                            undoDelegateTaskReason: data.reason
                        }
                    }
                )
                    .then((response) => {
                        this.$message.success(response.msg);
                        done();
                        this.getButtonAuth();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            // 委派
            delegateTask() {
                this.taskChange.choosePerson = true;
                this.taskChange.changeKey = 'delegate';
                this.taskChange.changeName = '委派';
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            // 委派回调函数
            delegate(data, done, errorDone) {
                request
                    .post(
                        website.baseCodeApiUrl + '/flow-task-change/delegate-task',
                        null,
                        {
                            params: {
                                taskId: this.keyInfo.taskId,
                                acceptUserId: data.acceptUser[0].id,
                                delegateTaskReason: data.reason
                            }
                        }
                    )
                    .then((response) => {
                        this.$message.success(response.msg);
                        done();
                        this.getButtonAuth();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            // 转办流程 转办后自己将不会托管 需要选择人
            turnTask() {
                this.taskChange.choosePerson = true;
                this.taskChange.changeKey = 'transferTransact';
                this.taskChange.changeName = '转办';
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            // 转办回调函数
            transferTransact(data, done, errorDone) {
                request
                    .put(
                        website.baseCodeApiUrl + '/flow-task-change/turn-task',
                        null,
                        {
                            params: {
                                taskId: this.keyInfo.taskId,
                                acceptUserId: data.acceptUser[0].id,
                                turnTaskReason: data.reason
                            }
                        }
                    )
                    .then((response) => {
                        this.$message.success(response.msg);
                        done();
                        this.getButtonAuth();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            // 加签
            addTask() {
                this.taskChange.choosePerson = true;
                this.taskChange.changeKey = 'addSign';
                this.taskChange.changeName = '加签';
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            // 加签回调函数
            addSign(data, done, errorDone) {
                request
                    .post(
                        website.baseCodeApiUrl + '/flow-task-change/add-task',
                        null,
                        {
                            params: {
                                processInstanceId: this.keyInfo.processInstanceId,
                                acceptUserId: data.acceptUser[0].id,
                                taskDefKey: this.buttonAuth.addTask.info,
                                addTaskReason: data.reason
                            }
                        }
                    )
                    .then((response) => {
                        this.$message.success(response.msg);
                        done();
                        this.getButtonAuth();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            // 减签
            deleteTask() {
                const loading = this.$loading({
                    lock: true,
                    text: '减签环节加载中',
                    spinner: 'el-icon-loading',
                    background: 'rgba(144, 146, 152, 0.3)'
                });
                request
                    .get(
                        website.baseCodeApiUrl +
                        '/flow-task-change/delete-task-list',
                        {
                            params: {
                                processInstanceId: this.keyInfo.processInstanceId,
                                taskDefKey: this.buttonAuth.deleteTask.info
                            }
                        }
                    )
                    .then((response) => {
                        loading.close();
                        this.taskChange.taskChangeInformationCollection.userArray =
                            response.data;
                        this.taskChange.choosePerson = true;
                        this.taskChange.changeKey = 'cancelAddSign';
                        this.taskChange.changeName = '减签';
                        this.taskChange.maxRows = 1;
                        this.taskChange.taskChangeInformationCollection.show = true;
                    })
                    .catch((error) => {
                        loading.close();
                        this.$message.error(error.msg || error.message);
                    });
            },
            // 减签回调函数
            cancelAddSign(data, done, errorDone) {
                request
                    .delete(
                        website.baseCodeApiUrl + '/flow-task-change/delete-task',
                        {
                            params: {
                                taskId: data.acceptUser,
                                deleteTaskReason: data.reason
                            }
                        }
                    )
                    .then((response) => {
                        this.$message.success(response.msg);
                        done();
                        this.getButtonAuth();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            // 终止流程
            termination() {
                this.taskChange.choosePerson = false;
                this.taskChange.changeKey = 'stop';
                this.taskChange.changeName = '终止申请';
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            // 终止流程回调函数
            stop(data, done, errorDone) {
                request
                    .delete(
                        website.baseCodeApiUrl +
                        '/flow-task-change/delete-process-instance',
                        {
                            params: {
                                processInstanceId: this.keyInfo.processInstanceId,
                                deleteReason: data.reason
                            }
                        }
                    )
                    .then((response) => {
                        this.$message.success('终止' + response.msg);
                        done();
                        this.getButtonAuth();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            revokePreTask() {
                this.taskChange.choosePerson = false;
                this.taskChange.changeKey = 'withdraw';
                let ruTaskInfo = this.buttonAuth.revokePreTask.info.ruTaskInfo
                    .map((item) => item.taskName)
                    .toString();
                let preTaskInfo = this.buttonAuth.revokePreTask.info.preTaskInfo
                    .map((item) => item.taskName)
                    .toString();
                this.taskChange.changeName = `从 ${ruTaskInfo} 撤回到 ${preTaskInfo}`;
                this.taskChange.taskChangeInformationCollection.labelName = '撤回';
                // 撤回的时候 拼接标题
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            revokeRefill() {
                this.taskChange.choosePerson = false;
                this.taskChange.changeKey = 'revokeRefillBack';
                // let ruTaskInfo = this.buttonAuth.revokePreTask.info.ruTaskInfo.map(item => item.taskName).toString()
                // let preTaskInfo = this.buttonAuth.revokePreTask.info.preTaskInfo.map(item => item.taskName).toString()
                this.taskChange.changeName = `撤回重填`;
                this.taskChange.taskChangeInformationCollection.labelName = '撤回';
                // 撤回的时候 拼接标题
                this.taskChange.maxRows = 1;
                this.taskChange.taskChangeInformationCollection.show = true;
            },
            // 撤回重填回调函数
            revokeRefillBack(data, done, errorDone) {
                console.log('撤回重填');
                if (this.keyInfo.processInstanceId) {
                    request
                        .get(
                            website.baseCodeApiUrl + '/flow-task-change/revoke-refill',
                            {
                                params: {
                                    processInstanceId: this.keyInfo.processInstanceId,
                                    revokePreTaskReason: data.reason
                                }
                            }
                        )
                        .then((response) => {
                            if (response.code === 200) {
                                request
                                    .get(
                                        website.baseCodeApiUrl +
                                        '/flow-ext/my-todo-and-wait-me-claim',
                                        {
                                            params: {
                                                pageNum: 1,
                                                pageSize: 1,
                                                processInstanceId:
                                                this.keyInfo.processInstanceId
                                            }
                                        }
                                    )
                                    .then((response) => {
                                        if (
                                            response.data.records &&
                                            response.data.records.length >= 1
                                        ) {
                                            let row = response.data.records[0];
                                            this.$router.push({
                                                name: 'workFlow-view-myApply',
                                                query: {
                                                    businessKey: row.businessKey,
                                                    processInstanceId: row.processInstanceId,
                                                    taskId: row.taskId,
                                                    formId: row.taskFormKey[0],
                                                    pageKey: 'DO'
                                                }
                                            });
                                            this.$message.success(response.msg);
                                            done();
                                        } else {
                                            this.$message.success(response.msg);
                                            done();
                                            this.getButtonAuth();
                                        }
                                        // 没有代办任务了, 返回主页, 查看详情
                                    });
                            } else {
                                this.$message.success(response.msg);
                                done();
                            }
                        })
                        .catch((error) => {
                            errorDone();
                            // this.$message.error(error.msg || error.message)
                        });
                }
            },
            // 撤回回调函数
            withdraw(data, done, errorDone) {
                console.log('撤回');
                if (
                    this.keyInfo.processInstanceId &&
                    this.buttonAuth.revokePreTask.info
                ) {
                    request
                        .post(
                            website.baseCodeApiUrl +
                            '/flow-task-change/revoke-per-task',
                            this.buttonAuth.revokePreTask.info,
                            {
                                params: {
                                    processInstanceId: this.keyInfo.processInstanceId,
                                    revokePreTaskReason: data.reason
                                }
                            }
                        )
                        .then((response) => {
                            if (response.code === 200) {
                                request
                                    .get(
                                        website.baseCodeApiUrl +
                                        '/flow-ext/my-todo-and-wait-me-claim',
                                        {
                                            params: {
                                                pageNum: 1,
                                                pageSize: 1,
                                                processInstanceId:
                                                this.keyInfo.processInstanceId
                                            }
                                        }
                                    )
                                    .then((response) => {
                                        if (
                                            response.data.records &&
                                            response.data.records.length >= 1
                                        ) {
                                            let row = response.data.records[0];
                                            this.$router.push({
                                                name: 'workFlow-view-myApply',
                                                query: {
                                                    businessKey: row.businessKey,
                                                    processInstanceId: row.processInstanceId,
                                                    taskId: row.taskId,
                                                    formId: row.taskFormKey[0],
                                                    pageKey: 'DO'
                                                }
                                            });
                                            this.$message.success(response.msg);
                                            done();
                                        } else {
                                            this.$message.success(response.msg);
                                            done();
                                            this.getButtonAuth();
                                        }
                                        // 没有代办任务了, 返回主页, 查看详情
                                    });
                            } else {
                                this.$message.success(response.msg);
                                done();
                            }
                        })
                        .catch((error) => {
                            errorDone();
                            // this.$message.error(error.msg || error.message)
                        });
                }
            },
            // 抄送回调函数
            cc(data, done, errorDone) {
                let userIdList = [];
                data.acceptUser.forEach((item) => {
                    userIdList.push(item.id);
                });
                request
                    .post(
                        website.baseCodeApiUrl + '/flow-cc-proc/to-users',
                        userIdList,
                        {
                            params: {
                                reCC: false,
                                processInstanceId: this.keyInfo.processInstanceId
                            }
                        }
                    )
                    .then((response) => {
                        this.$message.success(response.msg);
                        done();
                    })
                    .catch((error) => {
                        errorDone();
                        this.$message.error(error.msg || error.message);
                    });
            },
            imageLimited(file, column) {
                return new Promise(function (resolve) {
                    let reader = new FileReader();
                    reader.readAsDataURL(file);
                    let not = true;
                    reader.onload = function (theFile) {
                        let image = new Image();
                        image.src = theFile.target.result;
                        image.onload = function () {
                            let csize = `${this.width}*${this.height}`;
                            let limitSize = `${column.limitWidth}*${column.limitHeight}`;
                            if (csize !== limitSize) {
                                not = true;
                            } else {
                                not = false;
                            }
                        };
                    };
                    setTimeout(() => {
                        resolve(not);
                    }, 100);
                });
            },
            /**
             * 上传图片前 类型识别
             */
            async uploadBefore(file, done, loading, column) {
                /**
                 * 1、文档[doc、docx、xls、xlsx、ppt、pptx、txt、pdf、md];
                 *  2、图片[jpg、jpeg、png、gif、bmp];
                 * 3、视频[avi、mov、rmvb、rm、flv、mp4];
                 * 4、压缩包[rar、zip];
                 */
                if (column.limitWidth && column.limitHeight) {
                    const not = await this.imageLimited(file, column);
                    if (not) {
                        this.$message.error('图片尺寸不符规格限制');
                        loading();
                        return false;
                    }
                }
                let fileArr = [
                    'doc',
                    'docx',
                    'xls',
                    'xlsx',
                    'ppt',
                    'pptx',
                    'txt',
                    'pdf',
                    'md',
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                    'bmp',
                    'avi',
                    'mov',
                    'rmvb',
                    'rm',
                    'flv',
                    'mp4',
                    'rar',
                    'zip'
                ];
                let segs = file.name.split('.');
                if (segs.length <= 1) {
                    return (
                        this.$message.error('识别文件类型失败,请检查上传的文件类型') &&
                        loading()
                    );
                }
                if (fileArr.includes(segs.pop())) {
                    done();
                } else {
                    this.$message.error('文件格式不支持');
                    loading();
                }
            },

            handleSaveAndSubmit(){

            },
            /**
             * 是否 execl导出
             */
            canExport(type) {
                /** 有数据id才能导出 */
                if (
                    this.keyInfo.businessKey &&
                    (('execl' == type &&
                        Array.isArray(this.options['templatePathFileList']) &&
                        this.option['templatePathFileList'].length) ||
                        'pdf' == type)
                ) {
                    let exportType = this.option[`${type}Export`];
                    let exportConditions =
                        this.option[`${type}ExportConditions`];
                    if (exportType === 'notLimit') {
                        return true;
                    } else if (exportType === 'never') {
                        return false;
                    } else if (exportType === 'ongoing') {
                        // TODO 判断是否进行中
                        if (this.ProcessState === 'ongoing') return true;
                    } else if (exportType === 'completed') {
                        // TODO 判断是否已完成
                        if (this.ProcessState === 'completed') return true;
                    } else if (exportType === 'custom') {
                        try {
                            if (exportConditions) {
                                let replaceKey = exportConditions.match(/\${.*?}/g);
                                if (Array.isArray(replaceKey) && replaceKey.length) {
                                    replaceKey.forEach((item) => {
                                        let propKey = item.substring(2, item.length - 1);
                                        exportConditions = exportConditions.replace(
                                            item,
                                            `'${this.modelData[propKey]}'`
                                        );
                                    });
                                }
                                /* eslint-disable */
                                if (eval(exportConditions)) {
                                    return true;
                                }
                                /* eslint-enable */
                            }
                        } catch (error) {
                            console.error(`流程${type}下载自定义条件表达式出错`);
                        }
                    }
                }
                return false;
            }
        }
    };
</script>
<style lang="scss">
    .webapp {
        background-color: #fff;
        position: relative;
        width: 100%;
        height: 100%;

        .form-designer {
            height: 800px;
            overflow-y: scroll;
        }

        .form-designer .widget-config-container .el-tabs__header {
            position: relative;
        }
    }

    @media screen and (max-width: 760px) {
        .el-form-item{
            display: block !important;
            --font-size: 14px;
            margin-bottom: 0px!important;
            border-bottom: 1px solid #f8f8f8;
            background-color: #fff;
            padding: 10px 16px;
        }

        .el-col {
            margin-bottom: 0px;
        }

        .el-form-item--default{
            margin-bottom: 0px!important;
        }

        .basic-container__card {
            width: 100%;
            background-color: #f8f8f8;
        }


        html, body, #app {

            width: 100%;
            height: 100%;
            background-color: #f8f8f8!important;

        }

        .avue-group .el-collapse-item__wrap{
            border-color: #fff;
            border-radius: 10px;
            padding-bottom: 10px;
            margin-bottom: -10px;
        }


    }
</style>
